package com.codedancer.campus.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codedancer.campus.common.core.BaseMapper;
import com.codedancer.campus.po.ChatMessage;
import com.codedancer.campus.qo.chatMessage.ChatMessageSearchQo;
import org.apache.ibatis.annotations.Param;

public interface ChatMessageMapper extends BaseMapper<ChatMessage> {

    /**
     * 分页查询聊天记录
     *
     * @param chatMessagePage
     * @param chatMessageSearchQo
     * @return
     */
    IPage<ChatMessage> page(Page<ChatMessage> chatMessagePage,
        @Param("chatMessageSearchQo") ChatMessageSearchQo chatMessageSearchQo);

    /**
     * 分页查询聊天列表
     *
     * @param chatMessagePage
     * @param chatMessageSearchQo
     * @return
     */
    Page<ChatMessage> pageList(Page<ChatMessage> chatMessagePage,
        @Param("chatMessageSearchQo") ChatMessageSearchQo chatMessageSearchQo);

    /**
     * 查询某种聊天类型下聊天记录列表
     *
     * @param chatMessagePage
     * @param chatMessageSearchQo
     * @return
     */
    IPage<ChatMessage> pageByTypeUuid(Page<ChatMessage> chatMessagePage,
        @Param("chatMessageSearchQo") ChatMessageSearchQo chatMessageSearchQo);

    /**
     * 将用户收到的消息全部设置为已读
     *
     * @param currentUserUuid
     */
    default void setMessageReaded(String currentUserUuid, String receiveUserUuid) {
        LambdaUpdateWrapper<ChatMessage> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ChatMessage::getReceiveUserUuid, currentUserUuid);
        lambdaUpdateWrapper.eq(ChatMessage::getSendUserUuid, receiveUserUuid);
        lambdaUpdateWrapper.set(ChatMessage::getIsRead, true);
        update(null, lambdaUpdateWrapper);
    }

    /**
     * currentLoginUuid
     *
     * @param currentLoginUuid
     * @return
     */
    default Boolean isExitsNoRead(String currentLoginUuid) {
        LambdaQueryWrapper<ChatMessage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChatMessage::getReceiveUserUuid, currentLoginUuid);
        lambdaQueryWrapper.eq(ChatMessage::getIsRead, false);
        return selectCount(lambdaQueryWrapper) > 0;
    }

    /**
     * 两个用户之间是否存在未读消息
     *
     * @param chatUserUuid
     * @param currentUserUuid
     * @return
     */
    default Boolean isExitsNoReadBySendUuidAndReceiveUuid(String chatUserUuid,
        String currentUserUuid) {
        LambdaQueryWrapper<ChatMessage> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChatMessage::getSendUserUuid, chatUserUuid);
        lambdaQueryWrapper.eq(ChatMessage::getReceiveUserUuid, currentUserUuid);
        lambdaQueryWrapper.eq(ChatMessage::getIsRead, false);
        return selectCount(lambdaQueryWrapper) > 0;
    }

}
